const API = require('../../utils/api')
const pathUrl = require('../../utils/common.js')
Page({
  data: {
    coaches: [],
    searchKey: '',
    filter: '',
    page: 1,
    hasMore: true,
    loading: false
  },

  onLoad() {
    this.loadCoaches()
  },

  onShow() {
  },

  async loadCoaches(reset = true) {
    // 如果当前正在加载中，避免重复加载
    if (this.data.loading) return
    if (reset) {
      this.setData({ page: 1, hasMore: true })
    }
    if (!this.data.hasMore && !reset) return
    this.setData({ loading: true })
    API.coachList({
      name: this.data.searchKey,
      rating: this.data.filter=='rating'?1:'',
      price: this.data.filter=='price'?1:'',
      pageNum: this.data.page,
      pageSize: 10,
    }).then(res => {
      const newCoaches = res.records || [];

      console.log(newCoaches)
      // 处理图片路径
      for(let i=0; i<newCoaches.length; i++){
        if(newCoaches[i].avatar) {
          newCoaches[i].avatar = pathUrl + newCoaches[i].avatar;
        }
        newCoaches[i].price = newCoaches[i].price || 0;
        newCoaches[i].rating = newCoaches[i].rating || 5.0;
        newCoaches[i].reviewCount = newCoaches[i].reviewCount || 0;
      }
      
      // 根据返回的数据量判断是否还有更多数据
      const hasMoreData = newCoaches.length === 10
      
      this.setData({
        coaches: reset ? newCoaches : [...this.data.coaches, ...newCoaches],
        page: this.data.page + 1,
        hasMore: hasMoreData,
        loading: false
      })
    }).catch(err => {
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
      this.setData({ loading: false })
    })
  },

  onSearch(e) {
    this.setData({ searchKey: e.detail.value })
    this.loadCoaches()
  },

  setFilter(e) {
    const filter = e.currentTarget.dataset.filter
    this.setData({ filter: filter })
    this.loadCoaches()
  },

  goToCoachDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/coach-detail/coach-detail?id=${id}`
    })
  },

  loadMore() {
    this.loadCoaches(false)
  },

  onShareAppMessage() {
    return {
      title: '专业网球教练在线预约',
      path: '/pages/coaches/coaches',
      imageUrl: '/images/share-coach.jpg'
    }
  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 当页面滚动到底部时，加载更多数据
    this.loadMore()
  }
})